import pygame
from pygame.locals import *

class TextEntry(object):
	try:
		font = pygame.font.Font(None, 8)
	except:
		font = None
	
	def __init__(self, prompt, content="", function=None):
		self.prompt = prompt
		self.content = content
		self.function = function
		
		self.done = False
		
		self.text_size = self.font.get_height()
		self.surface = pygame.surface.Surface((200, self.text_size + 6))
	
	def draw(self, surface):	
		area = Rect(0, 0, 200, self.text_size+6)
		area.center = surface.get_rect().center
		pygame.draw.rect(surface, (0,0,0), area, 0)
		pygame.draw.rect(surface, (255,255,255), area, 1)
		oldclip = surface.get_clip()
		surface.set_clip(area.inflate(-4, -4))
		text = self.font.render("%s: %s" % (self.prompt, self.content), 1, (255,255,255), (0,0,0))
		surface.blit(text, area.move(5, 4))
		surface.set_clip(oldclip)
	
	def input(self, surface):
		while 1:
			self.draw(surface)
			pygame.display.update()
			
			event = pygame.event.wait()
			
			if event.type == pygame.QUIT:
				break
				
			if event.type != pygame.KEYDOWN:
				continue
				
			if event.key == pygame.K_BACKSPACE:
				self.content = self.content[:-1]
			elif event.key == pygame.K_RETURN:
				break
			elif event.unicode:
				self.content += event.unicode
			
		return self.content

	def event(self, event):
		if event.type == pygame.KEYDOWN:
			if event.key == pygame.K_BACKSPACE:
				self.content = self.content[:-1]
			elif event.key == pygame.K_RETURN:
				self.done = True
				self.function(self.content)
			elif event.unicode:
				self.content += event.unicode
			else:
				return False
			
			return True
		else:
			return False
